package com.wei.czz.framework.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wei.czz.common.enums.ResultEnum;
import com.wei.czz.common.enums.blog.BlogUserOperationEnum;
import com.wei.czz.common.enums.rabbitMQ.MqEnum;
import com.wei.czz.common.exception.CzzException;
import com.wei.czz.common.utils.SecurityUtils;
import com.wei.czz.common.vo.admin.BlogUserOperationVo;
import com.wei.czz.framework.common.helper.RabbitHelper;
import com.wei.czz.framework.rabbitMQ.message.blog.BlogOperationMessage;
import com.wei.czz.framework.blog.dao.BlogUserOperationDao;
import com.wei.czz.framework.blog.entity.BlogUserOperationEntity;
import com.wei.czz.framework.blog.service.BlogUserOperationService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wei
 * date: 2021-05-30 17:46:34
 * className: BlogUserOperationServiceImpl 用户操作博客请求服务接口实现类
 * version: 1.0
 * description:
 */
@Service("blogUserOperationService")
@AllArgsConstructor
public class BlogUserOperationServiceImpl extends ServiceImpl<BlogUserOperationDao, BlogUserOperationEntity>
        implements BlogUserOperationService {

    public static final Logger log = LoggerFactory.getLogger(BlogUserOperationServiceImpl.class);

    private final RabbitHelper rabbitHelper;

    @Override
    public Integer saveBlogUserOperation(BlogUserOperationEntity blogUserOpt) {
        int count = baseMapper.insert(blogUserOpt);
        log.info("添加用户操作博客记录完成。count={}", count);
        if (count == 0) {
            log.error("添加用户操作博客记录失败。{}", blogUserOpt);
        }
        return count;
    }

    @Transactional
    @Override
    public void saveUserBlogOperation(BlogUserOperationVo blogUserOperationVo) {

        // 获取当前正在执行用户关联博客操作的用户id
        Long optUserId = SecurityUtils.getUserId();
        // 博客id类型转换
        Long blogId = Long.parseLong(blogUserOperationVo.getBlogId());
        Date date = new Date();

        BlogOperationMessage blogOperationMessage = new BlogOperationMessage();
        // 设置博客id、用户id和操作类型（1-点赞/取消点赞 2-收藏/取消收藏）属性值
        blogOperationMessage.setBlogId(blogId)
                .setUpdateUserId(optUserId)
                .setOptType(blogUserOperationVo.getOptType());

        long count;
        if (blogUserOperationVo.getFlag()) {
            // 用户点赞/收藏博客
            BlogUserOperationEntity blogUserOperation = new BlogUserOperationEntity();
            // 设置用户id、博客id、操作类型（1-点赞 2-收藏）和操作时间属性值
            blogUserOperation.setUserId(optUserId)
                    .setBlogId(blogId)
                    .setOptType(blogUserOperationVo.getOptType())
                    .setOptTime(date);
            // 操作数据库用户操作博客表，新增一条用户操作博客记录信息
            count = baseMapper.insert(blogUserOperation);
            if (count == 0) {
                throw new CzzException("保存用户操作博客信息失败，请务必及时处理");
            }
            // 增加
            blogOperationMessage.setNum(1);

        } else {
            LambdaQueryWrapper<BlogUserOperationEntity> blogUserOptLambdaWrapper = new LambdaQueryWrapper<>();
            blogUserOptLambdaWrapper.select(BlogUserOperationEntity::getOptId);
            // 匹配 用户id、博客id和操作类型 字段
            blogUserOptLambdaWrapper.eq(BlogUserOperationEntity::getUserId, optUserId)
                    .eq(BlogUserOperationEntity::getBlogId, blogUserOperationVo.getBlogId())
                    .eq(BlogUserOperationEntity::getOptType, blogUserOperationVo.getOptType());
            // 查询数据库用户操作博客表，获取用户操作博客记录信息
            List<BlogUserOperationEntity> blogUserOperationList = this.list(blogUserOptLambdaWrapper);
            if (blogUserOperationList.isEmpty()) {
                String optType = blogUserOperationVo.getOptType().equals(BlogUserOperationEnum.LIKE_OPT.getValue()) ?
                        "点赞" : blogUserOperationVo.getOptType().equals(BlogUserOperationEnum.COLLECT_OPT.getValue()) ?
                        "收藏" : "";
                throw new CzzException(ResultEnum.REQUEST_FAIL.getCode(),
                        "您没有’" + optType + "‘操作记录，如有问题，请联系管理员处理！");
            }
            if (blogUserOperationList.size() > 1) {
                log.warn("用户对博客的同一种操作存在多条数据，请务必及时处理。{}", blogUserOperationVo);
            }
            BlogUserOperationEntity blogUserOperation = blogUserOperationList.get(0);
            // 操作数据库用户操作博客表，删除用户操作博客记录信息
            count = baseMapper.deleteById(blogUserOperation.getOptId());
            if (count == 0) {
                throw new CzzException("删除用户操作博客记录失败，请务必及时处理");
            }
            // 减少
            blogOperationMessage.setNum(-1)
                    .setOptTime(blogUserOperation.getOptTime());
        }

        // 发送一条消息到MQ中，异步更新系统博客的点赞/收藏数量
        rabbitHelper.send(MqEnum.USER_BLOG_OPT, blogOperationMessage);

    }

    @Override
    public Boolean getUserLikeBlog(Long userId, Long blogId) {

        Integer i = baseMapper.getUserLikeBlog(userId, blogId);

        return i > 0;
    }

    @Override
    public Boolean getUserCollectBlog(Long userId, Long blogId) {

        Integer i = baseMapper.getUserCollectBlog(userId, blogId);

        return i > 0;
    }

    @Override
    public List<BlogUserOperationEntity> getBlogUserOperationList(BlogOperationMessage blogOperationMessage) {
        LambdaQueryWrapper<BlogUserOperationEntity> blogUserOptLambdaWrapper = new LambdaQueryWrapper<>();
        // 查询 操作主键 字段
        blogUserOptLambdaWrapper.select(BlogUserOperationEntity::getOptId);
        // 匹配 用户id、博客id和操作类型 字段
        blogUserOptLambdaWrapper.eq(BlogUserOperationEntity::getUserId, blogOperationMessage.getUpdateUserId())
                .eq(BlogUserOperationEntity::getBlogId, blogOperationMessage.getBlogId())
                .eq(BlogUserOperationEntity::getOptType, blogOperationMessage.getOptType());
        // 查询
        List<BlogUserOperationEntity> blogUserOperationList = baseMapper.selectList(blogUserOptLambdaWrapper);
        if (blogUserOperationList.isEmpty()) {
            log.info("查询用户操作博客记录结果为空。{}", blogOperationMessage);
        }
        return blogUserOperationList;
    }

    @Override
    public int updateBlogUserOperation(BlogUserOperationEntity blogUserOpt) {
        int count = baseMapper.updateById(blogUserOpt);
        log.error("修改用户操作博客记录完成。count={}", count);
        if (count == 0) {
            log.error("修改用户操作博客记录失败。{}", blogUserOpt);
        }
        return count;
    }

}